package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;


@Component
@Slf4j
@Aspect
public class AutoFillAspect {
    /**
     * 切入点表达式：扫描mapper包下所有类和使用AutoFill注解进行增强
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void pt(){}

    /**
     * 前置通知
     * @param joinPoint
     */
    @Before("pt()")
    public void before(JoinPoint joinPoint){
        log.info("joinPoint: {}", joinPoint);

        //获取参数对象，填充公共字段
        //获取签名对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        //获取注解对象
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        //获取注解对象的值
        OperationType value = annotation.value();

        //获取原始方法的参数数组
        Object[] args = joinPoint.getArgs();
        //参数无效直接结束
        if (args == null || args.length == 0){
            return;
        }
        //获取第一个参数对象
        Object obj = args[0];

        //准备当前时间和当前对象id
        LocalDateTime nowTime = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();

            //判断是新增还是修改
        try {
            if(value == OperationType.INSERT){
                Method createTimeMethod = obj.getClass().getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method createUserMethod = obj.getClass().getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method updateTimeMethod = obj.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method updateUserMethod = obj.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                //执行反射语法 method.invoke(方法所属对象，数据值)
                createTimeMethod.invoke(obj,nowTime);
                createUserMethod.invoke(obj,currentId);
                updateTimeMethod.invoke(obj,nowTime);
                updateUserMethod.invoke(obj,currentId);

            } else {
                Method updateTimeMethod = obj.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method updateUserMethod = obj.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                updateTimeMethod.invoke(obj,nowTime);
                updateUserMethod.invoke(obj,currentId);
            }
        } catch (Exception e) {
           log.info("公共字段填充失败{}",e.getMessage());
        }

    }

}
